import axios from 'axios'
import type { AxiosRequestConfig, AxiosResponse } from 'axios'
import store from '@/store'
import { clearToken } from '@/store/modules/users'
console.log('import.meta.env', import.meta.env)
const instance = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  timeout: 5000,
})

instance.interceptors.request.use(
  (config) => {
    const { token } = store.getState().users
    if (config.headers) {
      config.headers.authorization = token
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

instance.interceptors.response.use(
  (response) => {
    if (response.data.errmsg === 'token error') {
      store.dispatch(clearToken())
      setTimeout(() => {
        window.location.replace('/login')
      }, 1000)
    } else if (response.data.errmsg === 'error') {
      //
    }
    return response
  },
  (error) => {
    return Promise.reject(error)
  }
)

interface Data {
  [index: string]: unknown
}

interface Http {
  get: (
    url: string,
    data?: Data,
    config?: AxiosRequestConfig
  ) => Promise<AxiosResponse>
  post: (
    url: string,
    data?: Data,
    config?: AxiosRequestConfig
  ) => Promise<AxiosResponse>
  put: (
    url: string,
    data?: Data,
    config?: AxiosRequestConfig
  ) => Promise<AxiosResponse>
  patch: (
    url: string,
    data?: Data,
    config?: AxiosRequestConfig
  ) => Promise<AxiosResponse>
  delete: (
    url: string,
    data?: Data,
    config?: AxiosRequestConfig
  ) => Promise<AxiosResponse>
}

const http: Http = {
  get(url, data, config) {
    return instance.get(url, {
      params: data,
      ...config,
    })
  },
  post(url, data, config) {
    return instance.post(url, data, config)
  },
  put(url, data, config) {
    return instance.put(url, data, config)
  },
  patch(url, data, config) {
    return instance.patch(url, data, config)
  },
  delete(url, data, config) {
    return instance.delete(url, {
      data,
      ...config,
    })
  },
}

export default http
